<?php
// +----------------------------------------------------------------------
// | 应用公共文件
// +----------------------------------------------------------------------
// | copyright (c) 2006-2016 http://thinkphp.cn all rights reserved.
// +----------------------------------------------------------------------
// | licensed ( http://www.apache.org/licenses/license-2.0 )
// +----------------------------------------------------------------------
// | author:
// +----------------------------------------------------------------------
//文件挂载位置 thinkphp/library/think/App.php:367
use app\model\Poster;
use think\Db;
use think\facade\log;
use think\facade\config;

error_reporting(E_ERROR);
//初始化系统全局变量
require_once APP_PATH . 'common/define_vars.php';
//初始化系统全局常量
require_once APP_PATH . 'common/define_constant.php';
//初始化全局函数
//数据库函数
require_once __DIR__ . '/common/functions_db.php';
//缓存函数
require_once __DIR__ . '/common/functions_cache_mysql.php';
//member 函数
require_once __DIR__ . '/common/functions_member.php';
//工具函数
require_once __DIR__ . '/common/functions_util.php';
//
require_once __DIR__ . '/common/functions_global.php';


/**
 * Desc:易宣日志记录
 * @param $txt
 * @param string $type
 * @return bool
 */
if (!function_exists('yxlog')) {
    function yxlog($txt, $type = '开发调试')
    {
        global $_G, $_P;
        $data['uniacid'] = $_G['mpid'];
        $data['themeid'] = intval($_P['themeid']);
        $data['type'] = $type;
        if (is_array($txt)) {
            $data['desc'] = json_encode($txt);
        } else {
            $data['desc'] = $txt;
        }
        $data['desc'] = '【' . SOFT_VERSION . '】' . $data['desc'];
        $data['user'] = !empty($_G['username']) ? $_G['username'] : 'UID:' . $_G['member']['uid'];
        $data['ip'] = $_G['clientip'];
        $data['addtime'] = TIMESTAMP;
        $data['url'] = $_G['url_scheme'] . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        if (!empty($_P['sdkv'])) {
            $data['url'] .= "&sdkv=" . $_P['sdkv'];
        }
        if (!empty($_P['m'])) {
            $r = Db::name(t_log)->insert($data);
        }
        if (empty($_P['m']) || in_array($type, ['支付差异订单', '小程序网络请求错'])) {
            Poster::Getbanklist($_G['system'], 'post_yxlog', $data);
        }
        return $r;
    }
}
/**
 * Desc:curl请求
 * User: yixuan
 * Time: 2016/5/18 16:09
 * @param $url
 * @param $post_data
 * @param $isjson
 * @param $header
 * @return bool|mixed|string
 */
if (!function_exists('yxcurl')) {

    function yxcurl($url, $post_data = [], $header = [], $isjson = false)
    {
        if (empty($post_data)) {
            $ispost = false;
        } else {
            $ispost = true;
        }
        $i = 1;
        while ($i <= 3) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
            curl_setopt($ch, CURLOPT_POST, $ispost);
            //不验证服务器证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            if ($ispost) {
                // This is a POST request
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            }
            if (!empty($header)) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            }
            // 在尝试连接时等待的秒数
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
            // 最大执行时间
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);

            // Fetch and return content
            $data = curl_exec($ch);
            // curl debug
            if (curl_errno($ch)) {
                $i++;
                yxlog($url, '请求出错');
                curl_close($ch);
            } else {
                curl_close($ch);
                break;
            }
        }
        if ($isjson) {
            $data = json_decode($data, true);
        }
        return $data;
    }
}
/**
 * Desc:数组转xml
 * User: yixuan
 * Time: 2016/6/8 13:21
 * @param $post
 * @return string
 */
if (!function_exists('to_xml')) {
    function to_xml($post)
    {
        $xml = "<xml>";
        foreach ($post as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
}
/**
 * Desc:xml转数组
 * Author: yixuan
 * Time: 2016/7/13 18:26
 * @param $xml
 * @return mixed
 */
if (!function_exists('xmlToArray')) {
    function xmlToArray($xml)
    {
        // 将XML字符串转换为SimpleXMLElement对象
        $simpleXml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        // 将SimpleXMLElement对象转换为关联数组
        return json_decode(json_encode((array)$simpleXml), true);
    }
}
/**
 * Desc:xml请求
 * User: yixuan
 * Time: 2016/6/8 13:22
 * @param $url
 * @param $xml
 * @param $pem
 * @param $second
 * @return bool|string|void
 */
if (!function_exists('yxcurl_xml')) {
    function yxcurl_xml($url, $xml, $pem = [], $second = 30)
    {
        if (is_array($xml)) {
            $xml = to_xml($xml);
        }
        $header[] = "Content-type: text/xml";
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //设置header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if (!empty($pem)) {
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLCERT, $pem['CURLOPT_SSLCERT']);
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLKEY, $pem['CURLOPT_SSLKEY']);
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($errno || empty($data)) {
            return ['errno' => $errno, 'message' => $error];
        }
        return $data;
    }
}

/**
 * Desc:易宣数据弹窗提醒方法
 * Author: yixuan
 * Time: 2016/5/27 10:07
 * @param $msg
 * @param $url
 * @param $type
 */
if (!function_exists('return_tips')) {
    function return_tips($msg = '操作成功', $url = '', $type = 'success')
    {
        global $_G, $_P;
        $data = [];
        $data['msg'] = $msg;
        $data['type'] = $type;
        if (\think\Request::instance()->isAjax()) {
            $data = [];
            $data['message'] = ['errno' => 0];
            $data['redirect'] = $url;
            $data['type'] = $type;
            exit(json_encode($data));
        }
        if (empty($url)) {
            $url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : referer();
        } else {
            if (strpos($url, 'http') === false) {
                if (strpos($url, '/') != 0) {
                    $url = $_G['url_domain'] . $url;
                } else {
                    $url = $_G['url_domain'] . substr($url, 1);
                }
            }
        }
        cookie($_G['username'] . 'return_tips', $data, 60);
        header("Location: $url");
        exit();
    }
}
/**
 * Desc:易宣数据单页面提示方法
 * Author: yixuan
 * Time: 2016/5/27 10:07
 * @param $msg
 * @param $url
 * @param $type  success|fail
 */
if (!function_exists('return_msg')) {
    function return_msg($msg = '操作成功', $url = '', $type = 'tips', $digit = 0)
    {
        global $_G;
        /**
         * $type = success|success-2|fail|fail-2
         */
        if (!empty($url)) {
            if (strpos($url, 'http') === false) {
                if (strpos($url, '/') != 0) {
                    $url = $_G['url_domain'] . $url;
                } else {
                    $url = $_G['url_domain'] . substr($url, 1);
                }

            }
        }

        if ($type == 'ajax') {
            $data = [];
            $data['message'] = $msg;
            $data['redirect'] = $url;
            $data['type'] = $type;
            exit(json_encode($data));
        }
        if (!empty($url) && $digit > 0) {
            $digit = $digit * 1000;
            $js = '
                <script type="text/javascript">
                    document.addEventListener("DOMContentLoaded", function () {
                         setTimeout(function() {
                                window.location.href = "' . $url . '"; // 替换为你的目标URL
                            }, ' . $digit . '); 
                    });
                </script>
            ';
        }
        $logo = $_G['companylogo'];
        if ($_G['app_web_wxapp'] == 'web') {
            $username = '<div class="dropdown-toggle"><i class="wi-user"></i>' . $_G['username'] . '<span class="caret"></span></div>';
        }
        if ($type == 'tips') {//提示
            if ($_G['app_web_wxapp'] == 'web') {
                $imgurl = 'css2020.yixuan.net/2020css/layui/info.png';
            } else {
                $imgurl = 'css2020.yixuan.net/2020css/layui/info2.png';
            }
        } else if ($type == 'success') {//成功
            $imgurl = 'css2020.yixuan.net/2020css/layui/success.png';
        } else if ($type == 'fail') {//失败
            $imgurl = 'css2020.yixuan.net/2020css/layui/error.png';
        } else {
            $imgurl = 'css2020.yixuan.net/2020css/layui/info.jpg';
        }
        if (empty($url)) {
            $url = 'javascript:history.back(-1)';
        }
        $imgurl = $_G['url_scheme'] . $imgurl;
        if ($_G['app_web_wxapp'] == 'web') {
            $html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0"><title>提醒</title><style>body{margin:0;padding:0}ul{list-style:none}a{text-decoration:none;color:white}a:hover{text-decoration:none}.header{width:100%;height:50px;background-color:#333847;display:flex;justify-content:space-between}.nav_r{display:flex}.usernames{color:white}.logo{padding:10px 15px;margin-left:0;height:50px}.searchBox{overflow:hidden;margin-top:10px;background:#fff;border-radius:30px;overflow:hidden;border:1px solid rgb(66,139,202);height:30px;width:235px}.searchBox input{font-size:14px;width:190px;height:30px;outline:none;line-height:30px;text-indent:0;float:right;border:none}.searchBox button{float:left;outline:none;width:30px;margin-left:5px;height:30px;border:none;background:url("' . $imgurl . '")center no-repeat;background-size:60%auto}.dropdown-toggle{line-height:50px;height:50px;padding:0 20px;max-width:200px;position:relative;overflow:hidden;white-space:nowrap;word-break:break-all;text-overflow:ellipsis;color:white}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.continer{width:100%;margin:0 auto;min-height:380px;background-color:white;position:relative}.content{width:600px;min-height:380px}.itu{width:100px;height:100px;margin:0px auto}.itu img{margin-top:50px;width:100px;height:100px}.font{padding-top:50px;text-align:center;font-size:25px;margin:50px auto;padding-bottom:150px}.buttons{width:300px;position:absolute;bottom:30px;left:0;right:0;text-align:center;margin:auto}.buttons button{background-color:#3782c0;border:1px solid gray;color:white;border-radius:3px;height:30px;border:0px}.buttons button:first-child{margin-right:10px}</style></head><body><div style="height: 100vh;width: 100%; background-color: #eeeeee;"><div class="header"><a href=""class="logo"><img src="' . $logo . '"alt=""style="height: 30px;"></a><div class="nav_r"><div class="dropdown">' . $username . '</div></div></div><div class="continer"><div class="itu"><img src="' . $imgurl . '"alt=""></div><div class="font"><div>' . $msg . '</div></div><div class="buttons"><button><a href="' . $url . '">点击这里返回上一页</a></button></div></div><div style="width: 100%; height: 200px;background-color: #f0f0f0;"></div></div></body></html>' . $js;
        } else {
            $html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0"><title>提醒</title><style>body{margin:0;padding:0}ul{list-style:none}a{text-decoration:none;color:white}a:hover{text-decoration:none}.header{width:100%;height:50px;background-color:#ffffff;display:flex;justify-content:space-between}.nav_r{display:flex}.searchBox input{font-size:14px;width:190px;height:30px;outline:none;line-height:30px;text-indent:0;float:right;border:none}.searchBox button{float:left;outline:none;width:30px;margin-left:5px;height:30px;border:none;background:url("' . $imgurl . '")center no-repeat;background-size:60%auto}.dropdown-toggle{line-height:50px;height:50px;padding:0 20px;max-width:200px;position:relative;overflow:hidden;white-space:nowrap;word-break:break-all;text-overflow:ellipsis;color:white}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.continer{width:100%;margin:0 auto;min-height:380px;background-color:white;position:relative}.itu{width:100px;height:100px;margin:0px auto}.itu img{margin-top:50px;width:100px;height:100px}.font{padding-top:50px;text-align:center;font-size:25px;margin:50px auto;padding-bottom:150px}.buttons{width:300px;position:absolute;bottom:30px;left:0;right:0;text-align:center;margin:auto}.buttons button{background-color:#50abf8;border:1px solid gray;color:white;border-radius:3px;height:32px;width:160px;border:0px}.buttons button:first-child{margin-right:10px}</style></head><body><div class="continer"><div class="itu"><img src="' . $imgurl . '"alt=""></div><div class="font"><div>' . $msg . '</div></div><div class="buttons"><button><a href="' . $url . '">点击这里返回上一页</a></button></div></div></div></div></body></html>' . $js;
        }
        exit($html);

    }
}


/**
 * Desc:随机字符串
 * User: yixuan
 * Time: 2016/5/9 09:52
 * @param $var
 * @param $allowget
 * @return bool|void
 */
if (!function_exists('random')) {
    function random($length, $numeric = FALSE)
    {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }
}
/**
 * Desc:随机字符串
 * User: yixuan
 * Time: 2016/5/9 09:52
 * @param $var
 * @param $allowget
 * @return bool|void
 */
if (!function_exists('referer')) {
    function referer($default = '')
    {
        global $_P, $_G;
        $_G['referer'] = !empty($_P['referer']) ? $_P['referer'] : $_SERVER['HTTP_REFERER'];
        $_G['referer'] = substr($_G['referer'], -1) == '?' ? substr($_G['referer'], 0, -1) : $_G['referer'];

        if (strpos($_G['referer'], 'member.php?act=login')) {
            $_G['referer'] = $default;
        }
        $_G['referer'] = $_G['referer'];
        $_G['referer'] = str_replace('&amp;', '&', $_G['referer']);
        $reurl = parse_url($_G['referer']);

        if (!empty($reurl['host']) && !in_array($reurl['host'], array($_SERVER['HTTP_HOST'], 'www.' . $_SERVER['HTTP_HOST'])) && !in_array($_SERVER['HTTP_HOST'], array($reurl['host'], 'www.' . $reurl['host']))) {
            $_G['referer'] = $_G['siteroot'];
        } elseif (empty($reurl['host'])) {
            $_G['referer'] = $_G['siteroot'] . './' . $_G['referer'];
        }
        return strip_tags($_G['referer']);
    }
}
/**
 * Desc:验证表单提交
 * User: yixuan
 * Time: 2016/5/9 09:52
 * @param $var
 * @param $allowget
 * @return bool|void
 */
if (!function_exists('checksubmit')) {
    function checksubmit($var = 'submit', $allowget = false)
    {
        global $_G, $_P;
        $token = input('__token__');
        $data = [
            '__token__' => $token,
        ];
        //验证路由
        $rule = [
            '__token__' => 'token',
        ];
        //错误信息
        $msg = [
            '__token__' => '请不要重复提交!',
        ];
        //引入验证类

        $validate = \think\Validate::make($rule, $msg);
        if ($validate->check($data) && !empty($token)) {
            $isValidate = true;
        }

        if (empty($_P[$var])) {
            return FALSE;
        }
        if (defined('IN_SYS')) {
            if ($allowget || (($_G['ispost']) && (empty($_SERVER['HTTP_REFERER'])
                        || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))) {

                return TRUE;
            }
        } else {
            if (empty($_G['isajax']) && !$isValidate) {

//                die('3');
                exit("<script type=\"text/javascript\">history.go(-1);</script>");
            } else {

//                die('4');
                unset($_SESSION['token'][$_P['token']]);
            }
//            die('5');
            return TRUE;
        }

        return FALSE;
    }
}
/**
 * Desc:分页
 * User: yixuan
 * Time: 2016/6/8 13:21
 * @param $total
 * @param $pageIndex
 * @param $pageSize
 * @param $url
 * @param $context
 * @return string
 */
if (!function_exists('pagination')) {
    function pagination($total, $pageIndex, $pageSize = 15, $url = '', $context = array('before' => 5, 'after' => 4, 'ajaxcallback' => '', 'callbackfuncname' => ''))
    {
        global $_G;
        $pdata = array(
            'tcount' => 0,
            'tpage' => 0,
            'cindex' => 0,
            'findex' => 0,
            'pindex' => 0,
            'nindex' => 0,
            'lindex' => 0,
            'options' => ''
        );
        if (empty($context['before'])) {
            $context['before'] = 5;
        }
        if (empty($context['after'])) {
            $context['after'] = 4;
        }

        if ($context['ajaxcallback']) {
            $context['isajax'] = true;
        }

        if ($context['callbackfuncname']) {
            $callbackfunc = $context['callbackfuncname'];
        }

        $pdata['tcount'] = $total;
        $pdata['tpage'] = (empty($pageSize) || $pageSize < 0) ? 1 : ceil($total / $pageSize);
        if ($pdata['tpage'] <= 1) {
            return '';
        }
        $cindex = $pageIndex;
        $cindex = min($cindex, $pdata['tpage']);
        $cindex = max($cindex, 1);
        $pdata['cindex'] = $cindex;
        $pdata['findex'] = 1;
        $pdata['pindex'] = $cindex > 1 ? $cindex - 1 : 1;
        $pdata['nindex'] = $cindex < $pdata['tpage'] ? $cindex + 1 : $pdata['tpage'];
        $pdata['lindex'] = $pdata['tpage'];

        if ($context['isajax']) {
            if (empty($url)) {
                $url = $_G['script_name'] . '?' . http_build_query($_GET);
            }
            $pdata['faa'] = 'href="javascript:;" page="' . $pdata['findex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['findex'] . '\', this);"' : '');
            $pdata['paa'] = 'href="javascript:;" page="' . $pdata['pindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['pindex'] . '\', this);"' : '');
            $pdata['naa'] = 'href="javascript:;" page="' . $pdata['nindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['nindex'] . '\', this);"' : '');
            $pdata['laa'] = 'href="javascript:;" page="' . $pdata['lindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['lindex'] . '\', this);"' : '');
        } else {
            if ($url) {
                $pdata['faa'] = 'href="?' . str_replace('*', $pdata['findex'], $url) . '"';
                $pdata['paa'] = 'href="?' . str_replace('*', $pdata['pindex'], $url) . '"';
                $pdata['naa'] = 'href="?' . str_replace('*', $pdata['nindex'], $url) . '"';
                $pdata['laa'] = 'href="?' . str_replace('*', $pdata['lindex'], $url) . '"';
            } else {
                $_GET['page'] = $pdata['findex'];
                $pdata['faa'] = 'href="' . $_G['script_name'] . '?' . http_build_query($_GET) . '"';
                $_GET['page'] = $pdata['pindex'];
                $pdata['paa'] = 'href="' . $_G['script_name'] . '?' . http_build_query($_GET) . '"';
                $_GET['page'] = $pdata['nindex'];
                $pdata['naa'] = 'href="' . $_G['script_name'] . '?' . http_build_query($_GET) . '"';
                $_GET['page'] = $pdata['lindex'];
                $pdata['laa'] = 'href="' . $_G['script_name'] . '?' . http_build_query($_GET) . '"';
            }
        }

        $html = '<div><ul class="pagination pagination-centered">';
        $html .= "<li><a {$pdata['faa']} class=\"pager-nav\">首页</a></li>";
        empty($callbackfunc) && $html .= "<li><a {$pdata['paa']} class=\"pager-nav\">&laquo;上一页</a></li>";

        if (!$context['before'] && $context['before'] != 0) {
            $context['before'] = 5;
        }
        if (!$context['after'] && $context['after'] != 0) {
            $context['after'] = 4;
        }

        if ($context['after'] != 0 && $context['before'] != 0) {
            $range = array();
            $range['start'] = max(1, $pdata['cindex'] - $context['before']);
            $range['end'] = min($pdata['tpage'], $pdata['cindex'] + $context['after']);
            if ($range['end'] - $range['start'] < $context['before'] + $context['after']) {
                $range['end'] = min($pdata['tpage'], $range['start'] + $context['before'] + $context['after']);
                $range['start'] = max(1, $range['end'] - $context['before'] - $context['after']);
            }
            for ($i = $range['start']; $i <= $range['end']; $i++) {
                if ($context['isajax']) {
                    $aa = 'href="javascript:;" page="' . $i . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $i . '\', this);"' : '');
                } else {
                    if ($url) {
                        $aa = 'href="?' . str_replace('*', $i, $url) . '"';
                    } else {
                        $_GET['page'] = $i;
                        $aa = 'href="?' . http_build_query($_GET) . '"';
                    }
                }
                if (!empty($context['isajax'])) {
                    $html .= ($i == $pdata['cindex'] ? '<li class="active">' : '<li>') . "<a {$aa}>" . $i . '</a></li>';
                } else {
                    $html .= ($i == $pdata['cindex'] ? '<li class="active"><a href="javascript:;">' . $i . '</a></li>' : "<li><a {$aa}>" . $i . '</a></li>');
                }
            }
        }

        if ($pdata['cindex'] < $pdata['tpage']) {
            empty($callbackfunc) && $html .= "<li><a {$pdata['naa']} class=\"pager-nav\">下一页&raquo;</a></li>";
            $html .= "<li><a {$pdata['laa']} class=\"pager-nav\">尾页</a></li>";
        }
        $html .= '</ul></div>';
        return $html;
    }
}
/**
 * Desc:阿里云oss上传
 * User: yixuan
 * Time: 2016/5/27 22:16
 * @param $path
 * @param $name
 * @return string|void
 */
if (!function_exists('file_remote_upload')) {
    function file_remote_upload($file, $auto_delete_local = true)
    {

        require_once VENDOR_PATH . '/alioss/autoload.php';
        $server_confg_t = Db::name('00serverconfig')->find();
        $server_confg = empty($server_confg_t) ? array() : json_decode($server_confg_t['config'], true);
        if (empty($server_confg)) {
            return false;
        }
        // 获取配置信息
        $accessKeyId = $server_confg['access_key_id'];
        $accessKeySecret = $server_confg['access_key_secret'];
        $endpoint = $server_confg['in_point'];//内网为in_point 外网为out_point
        $bucket = $server_confg['bucket'];

        try {
            // 创建OSSClient实例
            $ossClient = new OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            if (is_string($file)) {
                $file = str_replace(ATTACHMENT_ROOT, '', $file);
            }
            if (is_string($file) && file_exists(ATTACHMENT_ROOT . $file)) {
                $filename_arr = explode('.', $file);
                $filedir_arr = explode('/', $file);
                if (empty($filedir_arr[0])) {
                    file_delete($file);
                    return ['code' => -1, 'msg' => '文件目录不正确'];
                }
                $upload_type = end($filename_arr);
                if (empty($upload_type) || !in_array($upload_type, ['jpg', 'jpeg', 'png', 'gif', 'mp4', 'mp3'])) {
                    file_delete($file);
                    return ['code' => -1, 'msg' => '文件格式不正确：' . $upload_type];
                }
                // 文件名：年/月/唯一字符串/.文件类型
                $object = $filedir_arr[0] . "/" . date("Y") . '/' . date("m") . '/' . generate_uuid() . '.' . $upload_type;
                // 直接将临时文件上传到OSS
                $result = $ossClient->uploadFile($bucket, $object, ATTACHMENT_ROOT . $file);
                if ($auto_delete_local) {
                    file_delete($file);
                }
            } else {
                // 获取上传文件的信息
                $tmp_name = $file['tmp_name'];
                $filename_arr = explode('.', $file['name']);
                $file_type = end($filename_arr);
                if (!in_array($file_type, ['jpg', 'jpeg', 'png', 'gif', 'mp4', 'mp3'])) {
                    return ['code' => -1, 'msg' => '文件格式不正确：' . $file_type];
                }
                if (in_array($file_type, ['jpg', 'jpeg', 'png', 'gif'])) {
                    $main_path = "images/";
                } elseif ($file_type == 'mp4') {
                    $main_path = "videos/";
                } elseif ($file_type == 'mp3') {
                    $main_path = "audios/";
                } else {
                    return ['code' => -1, 'msg' => '文件流格式不正确:' . $file_type];
                }
                $server = explode('.', DOMAIN0)[0];
                $server = empty($server) ? 'public' : $server . "/";
                // 文件名：年/月/唯一字符串/.文件类型
                $object = $main_path . $server . date("Y") . '/' . date("m") . '/' . generate_uuid() . '.' . $file_type;
                // 直接将临时文件上传到OSS
                $result = $ossClient->uploadFile($bucket, $object, $tmp_name);
            }
            $oss_url = $server_confg['oss_domain'] . '/' . $object;
            if (strstr($oss_url, '.jpg') !== false) {
                $oss_url .= '/99.jpg';
            }
            return ['code' => 1, 'msg' => '上传成功', 'data' => ['url' => $oss_url]];
        } catch (OSS\Core\OssException $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}

/**
 * Desc:阿里云oss删除文件
 */
if (!function_exists('oss_delete')) {
    function oss_delete($path)
    {
        require_once VENDOR_PATH . '/alioss/autoload.php';
        $server_confg_t = Db::name('00serverconfig')->find();
        $server_confg = empty($server_confg_t) ? array() : json_decode($server_confg_t['config'], true);
        if (empty($server_confg)) {
            return false;
        }
        // 获取配置信息
        $accessKeyId = $server_confg['access_key_id'];
        $accessKeySecret = $server_confg['access_key_secret'];
        $endpoint = $server_confg['in_point'];//内网为in_point 外网为out_point
        $bucket = $server_confg['bucket'];
        $objectKey = $path; // 图片在OSS中的路径

        try {
            $ossClient = new OSS\OssClient($endpoint, $accessKeyId, $accessKeySecret);
            $ossClient->deleteObject($bucket, $objectKey);
            return ['code' => 1, 'msg' => "成功删除OSS上的对象：{$objectKey}\n"];
        } catch (OSS\Core\OssException $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}

/**
 * 随机32位字符串
 */
if (!function_exists('generate_uuid')) {
    function generate_uuid()
    {
        return sprintf('%04x%04x%04x%04x%04x%04x',
                mt_rand(0, 0xffff), mt_rand(0, 0xffff),
                mt_rand(0, 0xffff),
                mt_rand(0, 0x0fff) | 0x4000,
                mt_rand(0, 0x3fff) | 0x8000,
                mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
            ) . substr(uniqid(), 5);;
    }
}

if (!function_exists('generate_random_string')) {
    function generate_random_string($length = 10)
    {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            // 随机选取字符表中的一个字符
            $string .= $characters[mt_rand(0, strlen($characters) - 1)];
        }
        return $string;
    }
}

if (!function_exists('authcode')) {
    function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
    {
        $ckey_length = 4;
        $auth_key = config('database.serverkey') ? config('database.serverkey') : '4432a9d7';
        $key = md5($key != '' ? $key : $auth_key);
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if ($operation == 'DECODE') {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc . str_replace('=', '', base64_encode($result));
        }
    }
}

if (!function_exists('createWebUrl')) {
    function createWebUrl($do, $query = array(), $show_domain = false)
    {
        global $_G;
        if (empty($do)) {
            return "/";
        }
        if (empty($query['m'])) {
            $query['m'] = MODULE_NAME;
        }
        if (!empty($query)) {
            $queryString = http_build_query($query, '', '&');
        }
        $url = "/web/index.php?c=site&a=entry&do=" . $do . "&" . $queryString;
        $siteroot = substr($_G['siteroot'], 0, -1);
        return $show_domain ? $siteroot . $url : $url;
    }
}
if (!function_exists('createMobileUrl')) {
    function createMobileUrl($do, $query = array(), $show_domain = false)
    {
        global $_G, $_P;
        if (!empty($_P['isqr'])) {
            $query['isqr'] = 1;
        }

        $query['themeid'] = isset($query['themeid']) ? $query['themeid'] : 1;

        if (empty($query['fromuid'])) {
            $query['fromuid'] = intval($_G['member']['uid']);
        }
        $url = MODULE_NAME . "/" . $_G['mpid'] . "/" . $query['themeid'] . "/" . $query['fromuid'] . "/" . $do . ".aspx?";
        if (!empty($query['themeid'])) {
            $query['soft'] = $_G['theme']['softkey'];
        }

        unset($query['themeid']);
        unset($query['fromuid']);
        if (!empty($query)) {
            $url .= http_build_query($query, '', '&');
        }

        return $show_domain ? $_G['siteroot'] . $url : $url;
    }
}
if (!function_exists('createWebUrlPlugin')) {
    function createWebUrlPlugin($do, $query = array(), $show_domain = false)
    {
        $query = array_merge(['r' => $do], $query);
        $query = array_merge(['m' => MODULE_NAME], $query);
        return createWebUrl('web', $query, $show_domain);
    }
}
if (!function_exists('is_worker')) {
    function is_worker($themeid)
    {
        global $_G, $_P;
        $myworker = \app\model\Worker::getThemeWorkerByOpenidNew($_G['openid'], $themeid);
        if (empty($myworker) || $myworker['level'] > 3) {
            return false;
        }
        return true;
    }
}
//获取数组的层级
if (!function_exists('get_array_depth')) {
    function get_array_depth($array)
    {
        $maxDepth = 1;
        if (!is_array($array)) {
            return 0;
        }
        foreach ($array as $value) {
            if (is_array($value)) {
                $depth = get_array_depth($value) + 1;
                if ($depth > $maxDepth) {
                    $maxDepth = $depth;
                }
            }
        }
        return $maxDepth;
    }
}

if (!function_exists('authcode_yx')) {
    function authcode_yx($string, $operation = 'DECODE', $key = '', $expiry = 0)
    {
        // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
        $ckey_length = 4;

        // 密匙
        $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

        // 密匙a会参与加解密
        $keya = md5(substr($key, 0, 16));
        // 密匙b会用来做数据完整性验证
        $keyb = md5(substr($key, 16, 16));
        // 密匙c用于变化生成的密文
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
        // 参与运算的密匙
        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);
        // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，
        //解密时会通过这个密匙验证数据完整性
        // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);
        $result = '';
        $box = range(0, 255);
        $rndkey = array();
        // 产生密匙簿
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        // 核心加解密部分
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            // 从密匙簿得出密匙进行异或，再转成字符
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ($operation == 'DECODE') {
            // 验证数据有效性，请看未加密明文的格式
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
            // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
            return $keyc . str_replace('=', '', base64_encode($result));
        }
    }
}